package com.chinawayltd.ews.sample.web.order;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.model.TInterfaceLog;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.TOrder;
import com.chinawayltd.ews.sample.model.order.ExecuteDispatchVO;
import com.chinawayltd.ews.sample.model.order.InterfaceVO;
import com.chinawayltd.ews.sample.model.order.OrderDetailVO;
import com.chinawayltd.ews.sample.model.order.OrderVO;
import com.chinawayltd.ews.sample.service.algorithm.DispatchAlgorithmService;
import com.chinawayltd.ews.sample.service.common.CommonService;
import com.chinawayltd.ews.sample.service.order.OrderService;
import com.chinawayltd.ews.sample.util.BaseController;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.util.excel.ExcelGenerateModel;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExcelUtils;
import com.chinawayltd.ews.sample.web.query.InterfaceGirdQuery;
import com.chinawayltd.ews.sample.web.query.LogGirdQuery;
import com.chinawayltd.ews.sample.web.query.OrderDetailGirdQuery;
import com.chinawayltd.ews.sample.web.query.OrderGirdQuery;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description 物料订单订单信息Controller
 * @author: chenxin
 * @create: 2018年4月16日 下午5:16:47
 */
@Api(tags = { "物料订单信息管理API" })
@RestController
@RequestMapping(value = "/web/order")
public class OrderController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private OrderService orderService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private DispatchAlgorithmService dispatchAlgorithmService;

    private final String tableName = "T_ORDER";

    @ApiOperation(value = "执行订单任务调度")
    @RequestMapping(value = "/executeDispatch", method = { RequestMethod.POST })
    public ResultModel executeDispatch(@RequestBody  ExecuteDispatchVO queryParam) {
        ResultModel model = new ResultModel();
        try {
            dispatchAlgorithmService.executeDispatch(queryParam);
        }catch (BusinessException e){
            logger.info("执行订单任务调度业务异常：", e);
            model.setSub_code(1);
            model.setSub_msg(e.getMessage());
        }catch (Exception e){
            logger.error("执行订单任务调度系统发生异常:", e);
            model.setSub_code(ResultModel.SUB_CODE_SYSTEM_ERROR);
            model.setSub_msg(e.getMessage());
        }
        return model;
    }

    @ApiOperation(value = "物料订单信息列表查询接口")
    @RequestMapping(value = "/loadGirdData", method = { RequestMethod.POST })
    public ResultModel loadGirdData(OrderGirdQuery queryParam) {
    	ResultModel model = new ResultModel();
        try {
            List<OrderVO> orderList = orderService.listOrderByPage(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", orderList));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("物料订单列表查询出错！", e);
        }
        return model;
    }

    @ApiOperation(value = "物料订单信息异常列表查询接口")
    @RequestMapping(value = "/abnormal/loadGirdData", method = { RequestMethod.POST })
    public ResultModel loadAbnormalGirdData(OrderGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        try {
            List<OrderVO> orderList = orderService.listAbnormalOrderByPage(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", orderList));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("物料订单列表查询出错！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "调度信息列表查询接口")
    @RequestMapping(value = "/dispatch/loadGirdData", method = { RequestMethod.POST })
    public ResultModel dispatchLoadGirdData(InterfaceGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        try {
            List<InterfaceVO> interfaceList = orderService.dispatchLoadGirdData(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", interfaceList));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("调度信息列表查询出错！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "任务订单的物料订单信息")
    @RequestMapping(value = "/loadGirdDataForTask", method = { RequestMethod.POST })
    public ResultModel loadGirdDataForTask(OrderGirdQuery queryParam) {
    	ResultModel model = new ResultModel();
        try {
            List<OrderVO> orderList = orderService.listOrderByPage(queryParam);
            for (OrderVO orderVO : orderList) {
            	// 物料明细
                List<OrderDetailVO> list = orderService.listOrderDetailByOrderId(orderVO.getId());
                orderVO.setOrderDetailList(list);
			}
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", orderList));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
        }
        return model;
    }
    @ApiOperation(value = "根据ID查询单个物料订单信息")
    @RequestMapping(value = "/find/{id}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "id", value = "物料订单ID", dataType = "Long", required = true)
    public ResultModel getOrderById(@PathVariable Long id) {
    	ResultModel model = new ResultModel();
		try {
			TOrder data = orderService.getOrderById(id);
			model.setData(new JSONObject().fluentPut("result" , data));
        }catch (Exception e){
        	model.setSub_code(ResultModel.SUB_CODE_SYSTEM_ERROR);
			model.setSub_msg(e.getMessage());
        	logger.error("根据ID查询物料订单信息出错！id：" + id, e);
        }
        return model;
    }

    @ApiOperation(value = "新增物料订单信息", notes="orderNo-订单号</br>startPlace-取货站点id</br>"
    		+ "endPlace-送货站点id</br>orderDate-订单日期</br>earlyDeliveryTime-最早送货时间</br>"
    		+ "lastDeliveryTime-最晚送货时间</br>transportUnit-货物需运输板位数</br>applyDepartment-订单申请部门</br>"
    		+ "orderDetailList[0].id-物料明细id</br>orderDetailList[0].materielId-物料明细中的物料id，前台需从选中的物料信息中获取</br>"
    		+ "orderDetailList[0].planNumber-物料明细中的计划运输数量，前台需从选中的物料对应输入的数量获取</br>orderDetailList[0].actualNumber-物料明细中的实际运输数量，前台需从选中的物料对应输入的数量获取")
    @RequestMapping(value = "/add", method = { RequestMethod.POST})
    public ResultModel addOrder(@RequestBody OrderVO orderVO) {
    	ResultModel model = new ResultModel();
		try {
			orderService.insertOrder(orderVO);
			model.setData(new JSONObject().fluentPut("result" , "添加成功"));
        } catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
       	 	model.setSub_msg(e.getMessage());
        } catch (Exception e){
        	model.setSub_code(1);
        	model.setData(new JSONObject().fluentPut("sub_msg" ,  "添加失败"));
        	logger.error("新增物料订单时发生异常！", e);
        }
		return model;
    }

    @ApiOperation(value = "修改物料订单信息")
    @RequestMapping(value = "/update", method = { RequestMethod.POST })
    public ResultModel updateOrder(@RequestBody OrderVO orderVO) {        		
    	ResultModel model = new ResultModel();
		try {
			orderService.updateOrder(orderVO);
			model.setData(new JSONObject().fluentPut("result" , "修改成功"));
        }catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
       	 	model.setSub_msg(e.getMessage());
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg" , "修改物料订单信息发生异常！"));
        	logger.error("修改物料订单信息发生异常！"+e);
        }
		return model;
    }

    @ApiOperation(value = "删除订单信息")
    @RequestMapping(value = "/delete/{id}", method = { RequestMethod.DELETE })
    @ApiImplicitParam(paramType = "path", name = "id", value = "物料订单订单信息ID", dataType = "Long", required = true)
    public ResultModel deleteOrderById(@PathVariable Long id) {
    	ResultModel model = new ResultModel();
        try {
        	// 校验订单的状态是否是未生成
        	TOrder data = orderService.getOrderById(id);
        	if(data.getGenerateStatus() !=0){
        		throw new BusinessException("订单已调度，删除失败！");
        	}
        	// 删除订单信息
        	int result = orderService.deleteOrderById(id);
			if (result > 0) {
				model.setData(new JSONObject().fluentPut("result", "删除成功"));
			} else {
				model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
			}
        }catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
       	 	model.setSub_msg(e.getMessage());
        	logger.error("根据ID删除信息出错！id：" + id, e);
        }
		return model;
    }
    
    @ApiOperation(value = "通过ID查询操作日记接口")
    @RequestMapping(value = "/getLogDataById", method = { RequestMethod.POST })
    public ResultModel getLogDataById(LogGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        try {
        	queryParam.setTableName(tableName);
            List<TLog> list = commonService.getLogDataById(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , "查询失败"));
       	 	model.setSub_msg(e.getMessage());
            logger.error("通过ID查询操作日记接口异常！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "通过订单id查询订单和订单明细接口（用于编辑的回显）",notes="数据格式：result:{订单信息,orderDetailList:[订单的物料信息]}")
    @RequestMapping(value = "/listOrderAndDetailByOrderId/{orderId}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "orderId", value = "订单ID", dataType = "Long", required = true)
    public ResultModel listOrderAndDetailByOrderId(@PathVariable Long orderId) {
        ResultModel model = new ResultModel();
        try {
        	if(orderId == null || orderId <= 0){
                throw new RuntimeException("id不能为空或者少于等于0！");
            }
        	// 订单信息
        	OrderVO orderVO = orderService.listOrderByOrderId(orderId);
        	// 物料明细
            List<OrderDetailVO> list = orderService.listOrderDetailByOrderId(orderId);
            if(list.size() >0){
            	 orderVO.setOrderDetailList(list);
            }
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", orderVO));
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("通过订单id查询订单和订单明细接口！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "通过订单id查询物料订单明细接口（用于物料明细查看）")
    @RequestMapping(value = "/listOrderDetailByOrderId/{orderId}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "orderId", value = "订单ID", dataType = "Long", required = true)
    public ResultModel listOrderDetailByOrderId(@PathVariable Long orderId) {
        ResultModel model = new ResultModel();
        try {
            List<OrderDetailVO> list = orderService.listOrderDetailByOrderId(orderId);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("通过订单id查询物料订单明细接口！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "通过订单id分页查询物料明细，需要传订单id")
    @RequestMapping(value = "/listOrderDetailByPage", method = { RequestMethod.POST })
    public ResultModel listOrderDetailByPage(OrderDetailGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        try {
            List<OrderDetailVO> list = orderService.listOrderDetailByPage(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("通过订单id查询物料订单明细接口！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "物料订单信息管理导出接口")
    @RequestMapping(value = "/exportGirdData", method = { RequestMethod.POST })
    public void exportGirdData(@RequestBody OrderGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
        	List<OrderVO> list = orderService.listOrderByPage(queryParam);
            //List<Map<String, Object>> list = orderService.exportGirdData(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(list)
                    .cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "物料订单信息管理列表" , request, response);
        }catch (Exception e){
            logger.error("物料订单信息管理列表导出出错！", e);
        }
    }
    
    @ApiOperation(value = "异常物料订单信息管理导出接口")
    @RequestMapping(value = "/abnormal/exportGirdData", method = { RequestMethod.POST })
    public void abnormalExportGirdData(@RequestBody OrderGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
        	List<OrderVO> orderList = orderService.listAbnormalOrderByPage(queryParam);
        	//List<Map<String, Object>> orderList = orderService.abnormalExportGirdData(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(orderList)
                    .cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "异常物料订单信息管理列表" , request, response);
        }catch (Exception e){
            logger.error("物料订单信息管理列表导出出错！", e);
        }
    }
    
    @ApiOperation(value = "调度信息管理导出接口")
    @RequestMapping(value = "/dispatch/exportGirdData", method = { RequestMethod.POST })
    public void dispatchExportGirdData(@RequestBody InterfaceGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<InterfaceVO> list = orderService.dispatchLoadGirdData(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(list)
                    .cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "调度信息管理列表" , request, response);
        }catch (Exception e){
        	logger.error("物料订单信息管理列表导出出错！", e);
        }
    }
    
    /**
	 * 解析excel2003和2007的数据，并导入到数据库，错误数据导出到前台
	 * @author: chenxin
	 * @date: 2018年4月26日
	 * @param file
	 * @param request
	 * @param response
	 */
    @SuppressWarnings("rawtypes")
    @ApiOperation(value = "物料订单信息批量导入")
	@RequestMapping(value="/readExcel", method = { RequestMethod.POST })
    public Object readExcel(@RequestParam("file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
    	JSONObject object = new JSONObject();
    	try {
    		// 1、解析导入的数据
	    	ExcelObjModel model = ExcelUtils.readExcel(file);
			if(model.getCode() != 0){
				object.put("state", 400);
		    	object.put("msg", model.getMsg());
				return object.toString();
			}
			// 2、导入数据到数据库
			List<PageData> list = (List)model.getList();
			if(list ==null || list.isEmpty()){
				object.put("state", 400);
		    	object.put("msg", "导入的表不是有效的文件或数据为空");
		    	return object.toString();
			}
			//result = orderService.insertList(list);
			ExcelObjModel result = orderService.insertList2(list);
			// 3、导出错误数据
			if(result.getList().size() > 0){
		        ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(result.getList()).cloumnList(result.getCloums()).build();
		        Workbook workbook = ExcelUtils.generateExcel(excelModel);
				this.sendWorkbook(workbook, "物料订单信息" , request, response);
			}
		} catch (BusinessException e) {
		 	object.put("state", 400);
	    	object.put("msg", e.getMessage());
	    	return object.toString();
		} catch (IOException e) {
			object.put("state", 400);
	    	object.put("msg", "导入数据接口出错");
	    	return object.toString();
		} catch (Exception e) {
			logger.error("导入数据接口出错！", e);
		}
    	return null;
    }
    
    @ApiOperation(value = "查询调度情况")
    @RequestMapping(value = "/getTaskDispatch", method = { RequestMethod.GET })
    public ResultModel getTaskDispatch() {
    	ResultModel model = new ResultModel();
    	//Map<String, Object> map = new HashMap<>();
    	try {
			TInterfaceLog data = dispatchAlgorithmService.getTaskDispatch();//is_finish:0-否
			if(data ==null){
				data = new TInterfaceLog();
				data.setIsFinish((byte) 1);
//				map.put("status", data.getIsFinish());//
//				map.put("pro", data.getRateProgress() +"%");
//				map.put("token", data.getToken());
//				map.put("orderStartTimeStr", YYYYMMDD_HHMMSS.format(data.getOrderStartTime()));
//				map.put("orderEndTimeStr", YYYYMMDD_HHMMSS.format(data.getOrderEndTime()));
//				map.put("errorMsg", data.getErrorMsg());
			}
			model.setData(new JSONObject().fluentPut("result" , data));
        }catch (Exception e){
        	model.setData(new JSONObject().fluentPut("result" , null));
        	logger.error("查询调度情况异常", e);
        }
        return model;
    }
    @ApiOperation(value = "修改调度情况")
    @RequestMapping(value = "/updateTaskDispatch", method = { RequestMethod.GET })
    public ResultModel updateTaskDispatch() {
    	ResultModel model = new ResultModel();
    	try {
			dispatchAlgorithmService.updateTaskDispatch();
			model.setData(new JSONObject().fluentPut("result" ,"操作成功！"));
        }catch (Exception e){
        	model.setSub_code(ResultModel.SUB_CODE_SYSTEM_ERROR);
			model.setSub_msg(e.getMessage());
        	logger.error("修改调度情况异常", e);
        }
        return model;
    }
}
